/**
 * 一个简单的路由拦截器
 * @author 陈老师儿~
 * @mobile 18560000860
 */
import { getPage, isFunction, deepMerge } from "@/uni_modules/pure-utils";
export default {
	install(app, options) {
		// 默认配置
		let _config = {
			/**
			 * 前置路由拦截函数
			 * @param {Object} params 跳转参数，其中，另外增加了3个字段：
			 *                        1. from: 来源页面的配置信息
			 *                        2. to: 目标页面的配置信息
			 *                        3. type: 跳转类型，对应值：navigateTo、redirectTo、reLaunch、switchTab、navigateBack
			 * @returns {Boolean} true: 继续执行跳转，false: 终止跳转
			 */
			before: null,

			/**
			 * 后置路由拦截器函数
			 * @param {Object} pageJsonConfig 当前页面在 pages.json 中的配置信息
			 */
			after: null
		};

		// 合并配置
		_config = deepMerge(_config, options);

		/**
		 * 设置配置
		 * @param {Object} config 配置数据
		 */
		function setConfig(config = {}) {
			_config = deepMerge(_config, config);
		}

		// uni-app 路由
		const uniNavigateTo = uni.navigateTo;
		const uniRedirectTo = uni.redirectTo;
		const uniReLaunch = uni.reLaunch;
		const uniSwitchTab = uni.switchTab;
		const uniNavigateBack = uni.navigateBack;

		/**
		 * 重写 uni-app 路由
		 */
		uni.navigateTo = (params = {}) => {
			params.from = getPage();
			params.to = getPage(params.url);
			params.type = "navigateTo";
			if (beforeRouteTo(params)) uniNavigateTo(params);
		};

		uni.redirectTo = (params = {}) => {
			params.from = getPage();
			params.to = getPage(params.url);
			params.type = "redirectTo";
			if (beforeRouteTo(params)) uniRedirectTo(params);
		};

		uni.reLaunch = (params = {}) => {
			params.from = getPage();
			params.to = getPage(params.url);
			params.type = "reLaunch";
			if (beforeRouteTo(params)) uniReLaunch(params);
		};

		uni.switchTab = (params = {}) => {
			params.from = getPage();
			params.to = getPage(params.url);
			params.type = "switchTab";
			if (beforeRouteTo(params)) uniSwitchTab(params);
		};

		uni.navigateBack = (params = {}) => {
			params.from = getPage();
			params.to = getPrevPage();
			params.type = "navigateBack";
			if (beforeRouteTo(params)) uniNavigateBack(params);
		};

		/**
		 * 调用前置路由拦截函数
		 */
		function beforeRouteTo(params = {}) {
			if (isFunction(_config.before)) return _config.before(params);
			return true;
		}

		// 获取上一页在 pages.json 中定义的数据
		function getPrevPage() {
			const pages = getCurrentPages();
			const page = pages[pages.length - 2];
			if (!page) return null;
			const route = page?.route;
			return getPage(route);
		}

		app.mixin({
			onShow: () => {
				// 获取数据
				const currentPageJsonConfig = getPage();
				if (isFunction(_config?.after) && currentPageJsonConfig) {
					_config?.after(currentPageJsonConfig);
				}
			}
		});
	}
};
